package by.ostrovsky.webhousingsystem.bean.user;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import by.ostrovsky.webhousingsystem.bean.user.form.LoginBean;
import by.ostrovsky.webhousingsystem.constants.Constants;
import by.ostrovsky.webhousingsystem.controller.IUserController;
import by.ostrovsky.webhousingsystem.controller.account.LoginController;
import by.ostrovsky.webhousingsystem.crypt.SHACrypt;
import by.ostrovsky.webhousingsystem.exception.AccessDeniedException;
import by.ostrovsky.webhousingsystem.hibernate.entity.Account;

@SuppressWarnings("serial")
public class LoginAction extends LoginBean {
	private static Logger logger = Logger.getLogger(LoginAction.class);

	@Override
	public String execute() throws Exception {
		try {
			IUserController<Account, Boolean> controller = new LoginController();

			Account account = new Account();
			account.setId(getLogin());
			account.setHashed(SHACrypt.getInstance().encrypt(getPassword()));

			String level = controller.login(account);

			if (level == null || level == "")
				return Constants.FATAL;

			addSessionParameter(Constants.LEVEL, level);
			addSessionParameter(Constants.USERLOGIN, getLogin());

			String returnState = null;
			
			switch (level) {
			case Constants.LEVEL_USER:
				returnState = Constants.LEVEL_USER_SUCCESS;
				break;
			case Constants.LEVEL_PRIVILEGEDUSER:
				returnState = Constants.LEVEL_PRIVILEGEDUSER_SUCCESS;
				break;
			case Constants.LEVEL_MANAGER:
				returnState = Constants.LEVEL_MANAGER_SUCCESS;
				break;
			case Constants.LEVEL_ADMIN:
				returnState = Constants.LEVEL_ADMIN_SUCCESS;
				break;
			case Constants.LEVEL_ROOT:
				returnState = Constants.LEVEL_ADMIN_SUCCESS;
				break;
			default:
				returnState = Constants.FATAL;
				break;
			}
			
			ServletActionContext.getRequest().setAttribute(Constants.SUCCESS, null);
			ServletActionContext.getRequest().setAttribute(Constants.REASON, null);
			logger.info(Constants.USER_LOGGED_IN + ": " + returnState);
			return returnState;

		} catch (AccessDeniedException e) {
			ServletActionContext.getRequest().setAttribute(Constants.REASON, Constants.INCORRECT_DATA);
			return Constants.FAILURE;
		} catch (Exception e) {
			logger.error(e);
			return Constants.FATAL;
		}
	}
}
